# Copyright 2008 Ryan Whaley
# This file is part of gradient.
# 
# gradient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# gradient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with gradient.  If not, see <http://www.gnu.org/licenses/>.

import os

def getPoints(grade):
  if grade is None:
    return None
  gradeMap = {'F': 0, 'D': 1, 'C': 2, 'B': 3, 'A': 4}
  return gradeMap[grade]
  
def getLetterGrade(points):
  if points is None:
    return None
  if (points>=90):
    return 'A'
  elif (points>=80):
    return 'B'
  elif (points>=70):
    return 'C'
  elif (points>=65):
    return 'D'
  return 'F'

def gradeRecalc(course):
  if course.assignment_set != None:
    totalCorpus = 0
    totalCorpusScore = 0
    for assign in course.assignment_set:
      if (assign.amountOfCorpus != None):
        totalCorpus += assign.amountOfCorpus
      if (assign.amountOfCorpus != None and assign.score != None and assign.possible != None):
        totalCorpusScore += (assign.score/assign.possible)*assign.amountOfCorpus
    course.grade = getLetterGrade((totalCorpusScore*100)/totalCorpus)
    course.put()
    refreshSemData(course.semester)

def refreshSemData(semester):
  if semester.course_set != None:
    semester.gpa = -1.0
    
    totalPoints = 0
    totalHours = 0
    for course in semester.course_set:
      totalHours += course.hours
      totalPoints += getPoints(course.grade) * course.hours
    semester.semesterHours = totalHours
    semester.gpa = totalPoints/totalHours
  else:
    semester.semesterHours = 0.0
    semester.gpa = 0.0
    
  semester.put()
